﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;


namespace Kiva7.Utilities
{
    public class ScraperClient
    {
        [System.Security.SecuritySafeCritical]
        public ScraperClient()
        {
            CookieCollection = new Dictionary<string, Cookie>();
            CookieContainer = new CookieContainer();
        }

        private CookieContainer CookieContainer { get; set; }

        private Dictionary<string, Cookie> CookieCollection { get; set; }

        private void LoadCookies(HttpWebRequest request)
        {
            request.CookieContainer = new CookieContainer();
            foreach (KeyValuePair<string, Cookie> cookie in CookieCollection)
            {
                request.CookieContainer.Add(request.RequestUri, new Cookie(cookie.Value.Name, cookie.Value.Value));
            }
        }

        private void SaveCookies(HttpWebResponse response)
        {
            foreach (Cookie clientcookie in response.Cookies)
            {
                if (!CookieCollection.ContainsKey(clientcookie.Name))
                    CookieCollection.Add(clientcookie.Name, clientcookie);
                else
                    CookieCollection[clientcookie.Name] = clientcookie;
            }
        }

        public void HttpGet(Uri address, ScrapedHandler handler, object userToken)
        {
            HttpWebRequest request = GetWebRequest(address);
            GetResponse(handler, userToken, request);

        }

        private HttpWebRequest GetWebRequest(Uri address)
        {
            HttpWebRequest request = WebRequest.CreateHttp(address);
            request.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows Phone OS 7.5; Trident/5.0; IEMobile/9.0;";
            request.CookieContainer = CookieContainer;
            LoadCookies(request);
            return request;
        }

        public void HttpPost(Uri address, ScrapedHandler handler, PostDataBuilder postData, object userToken)
        {
            HttpWebRequest request = GetWebRequest(address);
            request.Method = "POST";
            //request.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
            request.ContentType = "application/x-www-form-urlencoded";
            byte[] data = Encoding.UTF8.GetBytes(postData.ToString());

            request.Headers[HttpRequestHeader.ContentLength] = data.Length.ToString();

            IAsyncResult iaresult = (IAsyncResult)request.BeginGetRequestStream(new AsyncCallback((asynchronousResult) =>
            {
                using (Stream stream = (Stream)request.EndGetRequestStream(asynchronousResult))
                {
                    stream.Write(data, 0, data.Length);
                }
                GetResponse(handler, userToken, request);
            }), null);

        }

        private void GetResponse(ScrapedHandler handler, object userToken, HttpWebRequest request)
        {
            IAsyncResult iaresult2 = (IAsyncResult) request.BeginGetResponse(new AsyncCallback((asynchronousResult2) =>
                {
                    HttpWebResponse response = (HttpWebResponse) request.EndGetResponse(asynchronousResult2);
                    SaveCookies(response);
                    using (StreamReader counter = new StreamReader(response.GetResponseStream()))
                    {
                        string result = counter.ReadToEnd();
                        handler.Invoke(result, response.ResponseUri, userToken);
                    }
                }), null);
        }

        public delegate void ScrapedHandler(string result, Uri responseUri, object userState);
    }
}
